package com.example.qqfake;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.AlertDialog;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements OnItemButtonClickListener{
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public Socket socket;
    private BufferedReader in;
    private PrintWriter out;


    private TextView tv_username;
    private TextView nicheng;
    private ImageView imageView;
    private ImageView geren;
    private ImageView friends;
    private RecyclerView recyclerView;
    private Adapter2 adapter;
    private List<User> userList = new ArrayList<>();
    private String username;
    private User myself;
    private  AlertDialog.Builder builder;
    private  AlertDialog.Builder builder1;
    private  AlertDialog.Builder builder3;
    private  String ip;
    private TextView dialogText;

    private String user_name;

    private final Object lock = new Object(); // 创建一个锁对象

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        // 初始化控件
        tv_username = findViewById(R.id.tv_username);
        nicheng = findViewById(R.id.nicheng);
        imageView = findViewById(R.id.myself);
        geren = findViewById(R.id.myhome);
        friends = findViewById(R.id.friend);


        // 从share中获取user_id
        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        username = sharedPreferences.getString("User_id","");
        user_name= sharedPreferences.getString("user_name","");



        myself = new User(Integer.parseInt(username));


        // 显示用户id
        if (username != null) {
            tv_username.setText(username);
        }
        // 显示用户名
        if (user_name != null) {
            nicheng.setText(user_name);
        }


        // 创建一个AlertDialog的构建器
        builder = new AlertDialog.Builder(this);

        // 设置对话框的标题
        builder.setTitle("提示");

        // 设置对话框的消息内容
        builder.setMessage("你想联系的对象不在线，请稍后重试");

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击了“取消”按钮
                // 对话框会自动关闭，无需额外处理
            }
        });

        // 创建一个AlertDialog的构建器
        builder1 = new AlertDialog.Builder(this);



        // 创建一个AlertDialog.Builder对象
        builder3 = new AlertDialog.Builder(this); // 'this' 替换为你的Activity或Fragment的上下文

        // 加载自定义布局
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.cache_dialog, null);

        dialogText = dialogView.findViewById(R.id.cache_content);

        // 设置自定义布局到AlertDialog中
        builder3.setView(dialogView);

        builder3.setTitle("收到消息如下：");


        builder3.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击了“取消”按钮
                // 对话框会自动关闭，无需额外处理
            }
        });








//        // 获取传递过来的图片Uri
//        String imageUriString = intent.getStringExtra("imageUri");
//        if (imageUriString != null) {
//            Uri imageUri = Uri.parse(imageUriString);
//            imageView.setImageURI(imageUri);
//        }

        // 设置点击事件
        tv_username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动资料编辑页面
                Intent profileIntent = new Intent(MainActivity.this, EditProfileActivity.class);
                profileIntent.putExtra("username", username); // 传递用户名
                startActivityForResult(profileIntent, 1); // 请求码为1
                MainActivity.this.finish();

            }
        });
        geren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动资料编辑页面
                Intent profileIntent = new Intent(MainActivity.this, EditProfileActivity.class);
                profileIntent.putExtra("username", username); // 传递用户名
                startActivityForResult(profileIntent, 1); // 请求码为1
                MainActivity.this.finish();

            }
        });
        friends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 启动联系人页面
                Intent profileIntent = new Intent(MainActivity.this, FriendActivity.class);
                profileIntent.putExtra("id",username); // 传递用户id
                startActivity(profileIntent); // 请求码为1
                MainActivity.this.finish();


            }
        });


        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new Adapter2(userList,this);
        recyclerView.setAdapter(adapter);


        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {


                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);


                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                //发送一条在线消息
                String message = "8,"+username+","+formattedString+","+username+"online"+","+username;
                out.println(message);
                //获取所有好友的信息
                userList.clear(); // 清空当前联系人列表
                String message1 = "7,"+username+","+formattedString+","+username+","+username;
                out.println(message1);
                //获取未接收的消息
                String message2 = "10,"+username+","+formattedString+","+username+","+username;
                out.println(message2);


                // 启动初始化的线程
                new Thread(this::Initmessage).start();
                /*
                * 由MainActivity发送的消息：
                * 1.在线消息，让服务器获取当前socket，当用户x在聊天页面发送消息，将由服务器转发到MainActivity,以对话框的形式出现：
                *           “你收到了来自xx的消息，是否进入与他的聊天界面”确定——>跳转到与x的聊天界面，关闭MainActivity的socket
                *            开启新的socket，此时若有用户c与你发消息，当前socket会检查send_id和现在聊天用户的id是否一致，如果不一致，
                *            也将以对话框的形式提醒用户。
                * 2.申请IP_chat消息，当用户想不经由服务器，与某个用户直接聊天，点击“地址”按钮向服务器发送IP地址请求，若对方在线，服务器将
                *                   请求“是否愿意与xx开启地址通信”转发给对方，当对方点击确认时（开启P2P通信b端），返回对方的IP地址，
                *                 （请求者开启P2P通信a端）两者可以进行地址通信
                *                    若对方不在线，或者拒绝了通信请求，服务器将返回失败，MainActivity接收false消息时，将提示用户...
                * 3.查找所有好友的请求，返回好友信息
                * */
                //启动 读取消息的线程
              //  new Thread(this::readMessge).start();


            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }).start();




    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 获取新用户名
            String newUsername = data.getStringExtra("newUsername");
            if (newUsername != null) {
                // 更新显示的用户名
                tv_username.setText(newUsername);
            }
            String newname = data.getStringExtra("name");
            if (newname != null) {
                // 更新显示的用户名
                nicheng.setText(newname);
            }

            // 获取新图片Uri
            String newImageUriString = data.getStringExtra("imageUri");
            if (newImageUriString != null) {
                Uri newImageUri = Uri.parse(newImageUriString);
                imageView.setImageURI(newImageUri);
            }
        }
    }





    @Override
    public void onItemButton2Click(int position) {
        String id = String.valueOf(userList.get(position).getId());
        Log.v("msg","ip_send");
        //发送IP请求消息消息
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedString = formatter.format(now);
        String message = "12,"+username+","+formattedString+","+"IP_chat"+","+id;


        Thread thread = new Thread(new Worker(message));
        thread.start();



    }
    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息
            out.println(message);
        }
    }





    private void Initmessage() {
        try {

            String message;
            while ((message = in.readLine()) != null) {
                Log.v("msg",message);
                if(message.equals("false6")){
                    Log.v("msg","no_friend");
                    break;
                }else if(message.equals("none_send")){
                    Log.v("msg","no_message");
                    break;
                }
                else if(message.contains("S@Y")){
                    Log.v("msg","somebody");
                    String[] data = message.split("S@Y");
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void run() {
                                dialogText.append(data[0]+":"+data[1]);
                                // 创建并显示对话框
                                AlertDialog dialog = builder3.create();
                                dialog.show();
                            }
                        });
                    }
                }
                else{
                        synchronized (lock) {
                            String[] data = message.split(" ");
                            User user = new User(Integer.parseInt(data[0]),data[1]);
                            if(!isFinishing()){
                                runOnUiThread(new Runnable() {//此run方法将由主线程运行
                                    @SuppressLint("NotifyDataSetChanged")
                                    @Override
                                    public void run() {
                                        //更新适配器的数据源
                                        adapter.addItem(user);

                                    }
                                });
                            }
                        }
                }


            }
            while((message = in.readLine()) != null){
                if(message.equals("false7")){
                    Log.v("msg1","ip_not_here");
                    //发送ip请求时，对方不在线
                    //提示对方不在线
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                // 创建并显示对话框
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        });
                    }
                    break;
                }else if(message.contains(",")) {
                    Log.v("msg","wneed");
                    //1.收到来自某个好友的消息（2）,发送id是好友的
                    //2.收到服务器发送的对方IP地址（2），发送id是自己的
                    //3.收到某个好友开启IP聊天的请求，发送id是好友的

                    String[] parts = message.split(",");
                    Content cc = new Content(parts[0], parts[1], parts[2], parts[3], parts[4]);
                    String finalContent = cc.getContent();
                    String who = cc.getSend_id();
                    String who_name = " ";
                    //找他的名字

                    //发送ip是自己
                    if (parts[1].equals(username)) {

                        for (User user : userList) {
                            if (user.getId() == Integer.parseInt(parts[4])) {
                                who_name = user.getUsername();
                                break; // 找到后立即退出循环
                            }
                        }
                        //接收IP地址
                        // 使用Handler延迟跳转
                        String finalWho_name1 = who_name;
                        // 创建Intent对象
                        Intent intent = new Intent(MainActivity.this, IPActivity.class);
                        ip = finalContent;
                        Log.v("msg", "get_IP");
                        // 处理第二个按钮--->地址聊天  的点击事件,跳转到对应的聊天对象

                        intent.putExtra("chat_partner", parts[4]);
                        intent.putExtra("chat_name", finalWho_name1);
                        //获取好友ip地址聊天-----IP地址
                        intent.putExtra("IP", ip);
                        Log.v("msg", "get_IP");
                        // 启动Activity
                        startActivity(intent);
                        // 关闭当前Activity
                        finish();

                    } else{
                        //好友消息，弹提示框
                        //遍历userList找到好友的name

                        for (User user : userList) {
                            if (user.getId() == Integer.parseInt(parts[1])) {
                                who_name = user.getUsername();
                                break; // 找到后立即退出循环
                            }
                        }
                        if (parts[3].contains("!!")) {

                            // 设置对话框的标题
                            builder1.setTitle("提示");


                            // 设置对话框的消息内容
                            builder1.setMessage(who_name + "想与你开启P2P通信");
                            Log.v("msg","get——IP");
                            String finalWho_name = who_name;
                            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 用户点击了确定按钮，跳转到IP_chat界面
                                    Intent intent = new Intent(MainActivity.this, IPActivity.class);

                                    intent.putExtra("chat_partner", who);
                                    intent.putExtra("chat_name", finalWho_name);
                                    startActivity(intent);
                                    MainActivity.this.finish();
                                }
                            });
                            if (!isFinishing()) {
                                runOnUiThread(new Runnable() {//此run方法将由主线程运行
                                    @Override
                                    public void run() {
                                        // 创建并显示对话框
                                        AlertDialog dialog = builder1.create();
                                        dialog.show();
                                    }
                                });
                            }



                        } else {

                            // 设置对话框的标题
                            builder1.setTitle("提示");

                            // 设置对话框的消息内容
                            builder1.setMessage("收到来自" + who_name + "的消息");


                            String finalWho_name = who_name;
                            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 用户点击了确定按钮，跳转到聊天界面
                                    Intent intent = new Intent(MainActivity.this, ChatActivity.class);

                                    intent.putExtra("chat_partner", who);
                                    intent.putExtra("chat_name", finalWho_name);
                                    intent.putExtra("content", finalContent);
                                    startActivity(intent);
                                    MainActivity.this.finish();

                                }
                            });
                            builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 用户点击了“取消”按钮
                                    // 对话框会自动关闭，无需额外处理
                                }
                            });
                            if (!isFinishing()) {
                                runOnUiThread(new Runnable() {//此run方法将由主线程运行
                                    @Override
                                    public void run() {
                                        // 创建并显示对话框
                                        AlertDialog dialog = builder1.create();
                                        dialog.show();
                                    }
                                });
                            }
                        }
                    }


                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }



//    private void readMessge() {
//        try {
//
//            String message;
//            while ((message = in.readLine()) != null) {
//                String[] parts = message.split(",");
//                String who_name = "";
//
//                for (User user : userList) {
//                    if (user.getId() == Integer.parseInt(parts[1])) {
//                        who_name = user.getUsername();
//                        break; // 找到后立即退出循环
//                    }
//                }
//                if (parts[3].contains("!!")) {
//
//                    // 设置对话框的标题
//                    builder1.setTitle("提示");
//
//
//                    // 设置对话框的消息内容
//                    builder1.setMessage(who_name + "想与你开启P2P通信");
//                    Log.v("msg","get——IP");
//                    String finalWho_name = who_name;
//                    builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            // 用户点击了确定按钮，跳转到IP_chat界面
//                            Intent intent = new Intent(MainActivity.this, IPActivity.class);
//
//                            intent.putExtra("chat_partner", parts[1]);
//                            intent.putExtra("chat_name", finalWho_name);
//                            startActivity(intent);
//                            MainActivity.this.finish();
//                        }
//                    });
//                    if (!isFinishing()) {
//                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
//                            @Override
//                            public void run() {
//                                // 创建并显示对话框
//                                AlertDialog dialog = builder1.create();
//                                dialog.show();
//                            }
//                        });
//                    }
//
//
//
//                } else {
//
//                    // 设置对话框的标题
//                    builder1.setTitle("提示");
//
//                    // 设置对话框的消息内容
//                    builder1.setMessage("收到来自" + who_name + "的消息");
//
//
//                    String finalWho_name = who_name;
//                    builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            // 用户点击了确定按钮，跳转到聊天界面
//                            Intent intent = new Intent(MainActivity.this, ChatActivity.class);
//
//                            intent.putExtra("chat_partner", parts[1]);
//                            intent.putExtra("chat_name", finalWho_name);
//                            intent.putExtra("content", parts[3]);
//                            startActivity(intent);
//                            MainActivity.this.finish();
//
//                        }
//                    });
//                    builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            // 用户点击了“取消”按钮
//                            // 对话框会自动关闭，无需额外处理
//                        }
//                    });
//                    if (!isFinishing()) {
//                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
//                            @Override
//                            public void run() {
//                                // 创建并显示对话框
//                                AlertDialog dialog = builder1.create();
//                                dialog.show();
//                            }
//                        });
//                    }
//                }
//
//
//                }
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    protected  void onStop(){
        super.onStop();
        try{

            if(socket!=null){
                socket.close();
                in.close();
                out.close();
            }

        }catch(IOException e){
            e.printStackTrace();

        }

    }


    //    //重写onDestroy()方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{

            if(socket!=null){
                socket.close();
                in.close();
                out.close();
            }

        }catch(IOException e){
            e.printStackTrace();

        }

    }

}
